package cn.kgc.junketing.consumerfeign.controller;

import cn.kgc.junketing.consumerfeign.entity.User;
import cn.kgc.junketing.consumerfeign.service.UserService;
import cn.kgc.junketing.consumerfeign.utli.CookieUtils;
import cn.kgc.junketing.consumerfeign.vo.ResponseBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {
    @Resource
    private UserService userService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/doLogin")
    @ResponseBody
    public ResponseBean doLogin(User user, HttpServletRequest request, HttpServletResponse response) {
        ResponseBean responseBean = this.userService.findLoginUser(user);
        //  响应给客户端
        if (responseBean.getCode() == 200)
            CookieUtils.setCookie(request, response, "ticket", responseBean.getObject().toString());
        return responseBean;
    }

    @RequestMapping("/toIndex")
    public String toIndex(Model model, NativeWebRequest webRequest, String userTicket) {
//        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//        String ticket = CookieUtils.getCookieValue(request, userTicket);
//        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
//        if (ticket == null) return null;
        User user = this.userService.doFindUserByTicket(userTicket);
//        if (user == null) return null;
//        CookieUtils.setCookie(request, response, userTicket, ticket);
        model.addAttribute("user", user);
        return "index";
    }
}
